import router from "./router";
import store from "./store";
import { toTree } from "@/utils/util";
const defaultRoutePath = "/dashboard/Workplace";
const whiteList = ["/login"];
let permissionData = {};
const pIdArray = [];
const firstLevel = [];
function getParents(parentId) {
  permissionData.map(result => {
    if (result.id === parentId) {
      pIdArray.push(result.id);
      if (result.parentId) {
        getParents(result.parentId);
      }
    }
  });
  console.log(permissionData);
}
const rootRouter = {
  name: "index",
  path: "/",
  component: () =>
    import(
      /* webpackChunkName: "home" */ "@/components/common/system/Home.vue"
    ),
  redirect: "/dashboard/Workplace",
  meta: {
    title: "首页"
  },
  children: []
};
const notFoundRouter = {
  path: "*",
  redirect: "/403",
  hidden: true
};
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  if (token) {
    if (to.path === "/login") {
      next({ path: defaultRoutePath });
    } else {
      if (store.getters.roles.length === 0) {
        //说明页面刷新了
        store.dispatch("GetInfo").then(res => {
          permissionData = res;
          let btnArray = res.filter(item => {
            return item.type === "BTN";
          });
          store.dispatch("btnArray", btnArray);
          res.map(result => {
            if (!result.parentId) {
              firstLevel.push(result); // 用于按照返回顺序存放一级菜单，防止左侧菜单栏混乱
            }
          });
          const selectedData = res
            .filter(res => res.selected)
            .filter(res => res.type !== "BTN");
          selectedData.map(result => {
            if (result.parentId) {
              getParents(result.parentId);
            }
          });
          pIdArray.map(resPid => {
            selectedData.push(res.filter(res => res.id === resPid)[0]);
          });
          // 先获取一级菜单跟有权限菜单的交集；防止一级菜单有没有权限的菜单，然后去重 生成该用户下所有有权限页面
          const roles = [
            ...new Set(
              firstLevel
                .filter(item => selectedData.indexOf(item) > -1)
                .concat(selectedData)
            )
          ];
          rootRouter.children = toTree(roles);
          const addRoutes = generator([rootRouter]);
          addRoutes.push(notFoundRouter);
          store.dispatch("SetSideBar", addRoutes);
          router.addRoutes(addRoutes);
          const redirect = decodeURIComponent(from.query.redirect || to.path);
          // 获取 当前登录的 配置的渠道
          if (to.path === redirect) {
            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            next({ ...to, replace: true });
          } else {
            // 跳转到目的路由
            next({ path: redirect });
          }
        });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      // 在免登录白名单，直接进入
      next();
    } else {
      localStorage.removeItem("tags");
      next({ path: "/login" });
    }
  }
});

router.afterEach(() => {});

function setName(str) {
  const arr = str.split("/");
  const arrLength = arr.length;
  return arr[arrLength - 1];
}

const generator = routerMap => {
  return routerMap.map(item => {
    // pathLength用于判断是否是全路径路由配置，若为全路径路由配置，可直接在component中使用
    const currentRouter = {
      path: item.path,
      name: setName(item.path),
      component: item.children
        ? item.component
          ? item.component
          : () => import("@/components/common/system/BlankLayout.vue")
        : () => import(`@/components/page${item.path}`),
      meta: {
        title: item.functionName,
        icon: item.icon || undefined,
        keepAlive: true,
        type: item.type
      }
    };

    if (!currentRouter.path.startsWith("http")) {
      currentRouter.path = currentRouter.path.replace("//", "/");
    }
    if (item.redirect) {
      currentRouter.redirect = item.redirect;
    }
    if (item.children && item.children.length > 0) {
      currentRouter.children = generator(item.children);
    }
    return currentRouter;
  });
};
